package com.nowcoder.controller;

import com.nowcoder.entity.Event;
import com.nowcoder.event.EventProducer;
import com.nowcoder.utils.CommunityConstant;
import com.nowcoder.utils.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ShareController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    EventProducer eventProducer;

    @Value("${community.path.domain}")
    String domain;

    @Value("${wk.image.data}")
    String wkData;

    @Value("${E:/Tools/wkhtmltopdf/bin/wkhtmltoimage.exe}")
    String wkCmd;

    @Value("${qiniu.url.share}")
    String qiNiuUrlShare;


    @GetMapping("/share")
    @ResponseBody
    public String share(String htmlUrl) {
        String filename = CommunityUtil.generateUUID();
        Event event = new Event()
                .setTopic(CommunityConstant.TOPIC_SHARE)
                .setData("htmlUrl", htmlUrl)
                .setData("filename", filename)
                .setData("suffix", ".png");
        eventProducer.fireEvent(event);
        // 设置访问路径
        Map<String, Object> map = new HashMap<>();
        map.put("shareUrl", domain + "/share/image/" + filename + ".png");
        String uuid = CommunityUtil.generateUUID();
        map.put("shareUrl", qiNiuUrlShare + "/" + filename);

        return CommunityUtil.getJSONString(0, null, map);
    }

    @Deprecated
    @GetMapping("/share/image/{fileName}")
    public void getShareImage(@PathVariable("fileName") String fileName,
                              HttpServletResponse response) {
        if (StringUtils.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名不能为空!");
        }

        response.setContentType("image/png");
        File file = new File(wkData + "/" + fileName);
        try {
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("获取长图失败: " + e.getMessage());
        }
    }


}
